//
//  FunningCameraController.m
//  vImageStudy
//
//  Created by Evan Xie on 8/13/15.
//  Copyright (c) 2015 Family Wings. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "FunningCameraController.h"
#import "CameraPreviewView.h"

@interface FunningCameraController ()
{
    AVCaptureDevice *_captureDevice;
    AVCaptureDeviceInput *_captureDeviceInput;
    AVCaptureSession *_captureSession;
    AVCaptureStillImageOutput *_stillImageOutput;
    
    dispatch_queue_t _sessionQueue;
}

@property (nonatomic) CameraPreviewView *previewView;

@end

@implementation FunningCameraController

- (void)viewDidLoad {
    [super viewDidLoad];

    _sessionQueue = dispatch_queue_create("sessionqueue", DISPATCH_QUEUE_SERIAL);
    
    _previewView = [[CameraPreviewView alloc] initWithFrame:self.view.bounds];
    _previewView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_previewView];
    
    _captureSession = [[AVCaptureSession alloc] init];
    _previewView.session = _captureSession;
    
    dispatch_async(_sessionQueue, ^{
        
        NSArray *mediaDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        _captureDevice= mediaDevices.firstObject;
        for (AVCaptureDevice *device in mediaDevices) {
            if (device.position == AVCaptureDevicePositionBack) {
                _captureDevice = device;
                break;
            }
        }
        
        NSError *error;
        _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:&error];
        if (error) {
            NSLog(@"GEt device input failed: %@", error);
        }
        
        if ([_captureSession canAddInput:_captureDeviceInput]) {
            [_captureSession addInput:_captureDeviceInput];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[(AVCaptureVideoPreviewLayer *)self.previewView.layer connection] setVideoOrientation:(AVCaptureVideoOrientation)self.interfaceOrientation];
            });
        }
        
        _stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
        if ([_captureSession canAddOutput:_stillImageOutput]) {
            _stillImageOutput.outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG};
            [_captureSession addOutput:_stillImageOutput];
        }
        
        [_captureSession startRunning];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
